/**
 * 所以请求拦截器
 */
import {extend} from "umi-request";
import {message} from "antd";
import {history} from "umi";
import {stringify} from "querystring";
import * as process from "process";

const request = extend({
  credentials: 'include',
  // 区分多环节
  prefix: process.env.NODE_ENV  === 'production' ? undefined : undefined
});

request.interceptors.request.use((url, options): any => {
  console.log(`do request url =${url}`);
  return {
    url,
    options: {
      ...options,
      headers: {
      },
    },
  };
});

/**
 * 所有响应拦截器
 */
request.interceptors.response.use(async (response, options): Promise<any> => {
  const res = await response.clone().json();
  console.log(res.code)
  if(res.code === 0){
    return res.data;
  }
  if (res.code === 40002){
    message.error("请先登录")
    history.replace({
      pathname: '/user/login',
      search: stringify({
        redirect: location.pathname,
      })
    })
  }else{
    message.error(res.description);
  }
  return res.data;
});

export default request;
